<?php

namespace app\v1\model;

use think\Model;

/**
 * 客房模型类
 */
class Rooms extends Model
{
    /**
     * 获取所有客房列表
     */
    public function GetList($page, $option = []) 
    {
        // 创建匿名函数 方便多次调用 用完自动销毁
        $buildDb = function () use ($option) {
            $db = $this
                ->alias('r')
                ->field('r.*, ri.url')
                ->where('r.state', 1)
                ->field('s.name specifications_name')
                ->join('specifications s', 's.id = r.specifications_id', 'LEFT')
                ->where('s.state', 1);

                // 根据地区id查询
            if (array_key_exists('region_id', $option) && !empty($option['region_id'])) {
                // 判断有无子地区
                $regionArray = db('region')->where('parent_id', $option['region_id'])->column('id');

                if (count($regionArray) == 0)  {
                    $regionArray[] = $option['region_id'];
                } else {
                    $regionArray[] = $option['region_id'];   
                }
                $db = $db->whereIn('r.region_id',  $regionArray);
            }
            // 根据规格id查询
            if (array_key_exists('specifications_id', $option) && !empty($option['specifications_id'])) {
                $db = $db->where('r.specifications_id', $option['specifications_id']);
            }

            if (array_key_exists('start_time', $option) && !empty($option['start_time'])) {
                $roomsIdArray = db('rooms_user')
                    ->whereTime('start_time', '>=', $option['start_time'])
                    ->whereTime('end_time', '<=', $option['end_time'])
                    ->where('state', '<>', 0)
                    ->column('rooms_id');
                if (count($roomsIdArray) > 0) {
                    $db = $db->whereNotIn('id', $roomsIdArray);
                }
            }
            return $db->join('rooms_img ri', 'ri.rooms_id = r.id', 'LEFT')->group('r.id');
        };
        // 获取符合条件的数据总数
        $count = $buildDb()->count();
        // 获取符合条件的数据列
        $list = $buildDb()
            ->field('re.name region_name')
            ->join('region re', 're.id = r.region_id', 'LEFT')
            ->page($page, 20)
            ->select();
        
        // 将数据转换为数组格式
        if ($list) {
            $list = $list->toArray();
        }
        return Result(1, '', [
            'count' => $count,
            'pageSize' => 20,
            'list'   => $list
        ]);
    }

    /**
     * 获取指定数据
     */
    public function GetInfo($id) 
    {
        if ($this->where('id', $id)->count() == 0) {
            return Result(0, '该民宿不存在');
        }
        
        $rooms = $this
                ->alias('r')
                ->field('r.*, s.name specifications_name, re.name region_name')
                ->join('specifications s', 'r.specifications_id = s.id', 'LEFT')
                ->join('region re', 'r.region_id = re.id', 'LEFT')
                ->where(['r.id' => $id , 's.state' => 1, 'r.state' => 1])
                ->find();
        // 获取所有客房图片
        $rooms['image'] = db('rooms_img')->where([ 'rooms_id' => $id, 'state' => 1])->column('url');

        return Result(1, '', [
            'rooms' => $rooms
        ]);
    }

    /**
     * 
     * 创建订单
     */
    public function ReservationRooms($roomsId, $userId, $start_time, $end_time, $mobile = 0)
    {
        // 查询该房间在指定时间是否存在
        $criteria = db('rooms_user', [], false)
            ->where('rooms_id', $roomsId)
            ->where('state', '<>', 0)
            ->whereTime('start_time', '>=', $start_time)
            ->whereTime('end_time', '<=', $end_time)
            ->count() > 0;
        
        if ($criteria) {
            return Result(0, '该房间已被预订');
        }
        // 获取房间信息
        $rooms = $this->where('id', $roomsId)->find()->toArray();
        if (empty($mobile)) {
            $mobile = db('user')->where('id', $userId)->value('mobile');
        }
        // 计算天数
        $day = round((strtotime($end_time) - strtotime($start_time)) / 3600 / 24);
        //入库
        $id = db('rooms_user', [], false)->insertGetId([
            'rooms_id' => $roomsId,
            'user_id' => $userId,
            'start_time' => $start_time,
            'end_time' => $end_time,
            'mobile' => $mobile,
            'price' => $rooms['price'],
            'day' => $day,
            'price_num' => $day * $rooms['price']
        ]);

        return Result(1, '预定成功', [
            'id' => $id
        ]);
    }
    
    /**
     * 查询指定条件下的空房间
     */
    public function GetEmptyRoomsList($page, $option)
    {
        // 创建匿名函数 方便多次调用 用完自动销毁
        $buildDb = function () use ($option) {
            $db = $this
                ->alias('r')
                ->field('r.*, s.name specifications_name, re.name region_name,ri.url,rp.name parent_name')
                ->join('specifications s', 'r.specifications_id = s.id', 'LEFT')
                ->join('region re', 'r.region_id = re.id', 'LEFT')
                ->join('region rp', 're.parent_id = rp.id', 'LEFT')
                ->join('rooms_img ri', 'r.id = ri.rooms_id', 'LEFT')
                ->where('r.state', 1);

            // 根据入住和离开时间查询
            if (array_key_exists('start_time', $option) && array_key_exists('end_time', $option)){
                // 查询该时间段已被预定的房间
                $roomsIdArr = db('rooms_user')
                    ->whereTime('start_time', '>=', $option['start_time'])
                    ->whereTime('end_time', '<=', $option['end_time'])
                    ->where('state', '<>', 0)
                    ->column('rooms_id');
                // 排除这些房间
                if(count($roomsIdArr)) {
                    $db = $db->whereNotIn('id', $roomsIdArr);
                }
            }

            // 根据地区查询房间
            if (array_key_exists('region_id', $option) && !empty($option['region_id'])) {

                $regionArray = db('region')->where('parent_id', $option['region_id'])->column('id');

                if (count($regionArray) == 0)  {
                    $regionArray[] = $option['region_id'];
                } else {
                    $regionArray[] = $option['region_id'];   
                }
                $db = $db->whereIn('r.region_id',  $regionArray);
            }
            
            //根据规格查询房间
            if (array_key_exists('specifications_id', $option) && !empty($option['specifications_id'])) {
                $db = $db->where('r.specifications_id', $option['specifications_id']);
            }

            return $db->group('r.id');
        };

        $count = $buildDb()->count();
        $list = $buildDb()->page($page, 20)->select();

        return Result(1, '', [
            'count' => $count,
            'pageSize' => 20,
            'list' => $list
        ]);
    }
}
